#  Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
#  Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
#  Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
#  Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
#  Vestibulum commodo. Ut rhoncus gravida arcu.
from datetime import datetime

from Cryptodome import Random
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import  PKCS1_v1_5
import base64
from urllib import parse
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from api.models import user,sig_user_task,sig_user_jl
from django.core import serializers
import json
import requests
import hashlib
import os
import time


def time_b_z_s(A,B,C):
    print(A)
    print(B)
    print(C)
    A = str(A).split(':')
    A = int(int(A[0])*60*60)+int(int(A[1])*60)+int(A[2])
    print(str(A))
    B = str(B).split(':')
    B = int(int(B[0]) * 60 * 60) + int(int(B[1]) * 60) + int(B[2])
    print(str(B))
    C = str(C).split(':')
    C = int(int(C[0]) * 60 * 60) + int(int(C[1]) * 60) + int(C[2])
    print(str(C))
    if B>=A and B <=C:
        return True
    else:
        return False



def User_if(request):
    if request.method == 'POST':
        # 多少的看看有没有登记过信息如果有直接登录没有在向用户去获取信息
        Code =  decrypt_data(eval(request.body)['code'])
        Url_ = ("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" % (
                'wx83998a37ca84ecf1', '8bbd3f4d4b39461f68858f7c28429ca0', Code))
        RESs = requests.get(url=Url_)
        date = json.loads(RESs.content)
        try:
            isuser = user.objects.get(OpenID=date['openid'])
            isuser.token = hashlib.sha1(os.urandom(24)).hexdigest()
            isuser.save()
            isuser2 = user.objects.get(OpenID=date['openid'])
            return JsonResponse({
                'code': '0031',
                'data': {
                    'isuer':True,
                    'data': {
                        'jifen': isuser2.jifen,
                        'name': isuser2.nickName,
                        'headimg': isuser2.avatarUrl,
                        'id': isuser2.id,
                        'token': isuser2.token,
                        'openid': isuser2.OpenID,
                    }
                },
                'msg': '用户查询成功'
            })
        except:
            return JsonResponse({
                'code': '0031',
                'data': {
                    'isuer':False,

                },
                'msg': '没有此用户'
            })
    else:
        return JsonResponse({
            'code': '0000',
            'data': 'null',
            'msg': '非法请求'
        })





# Create your views here.
def User_log(request):
    if request.method == 'POST':
        # print(request)
        # if request.POST:
        # Code = request.get_port('code')
        Code =decrypt_data(eval(request.body)['code'])
        data_post = eval(request.body)
        Url_ = ("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" % (
            'wx83998a37ca84ecf1', '8bbd3f4d4b39461f68858f7c28429ca0', Code))
        RESs = requests.get(url=Url_)
        print(request.body)
        date = json.loads(RESs.content)
        try:
            user1 = user.objects.get(OpenID=date['openid'])
            user1.session_key = date['session_key']
            user1.avatarUrl = decrypt_data(data_post['avatarUrl'])
            user1.city = decrypt_data(data_post['city'])
            user1.country = decrypt_data(data_post['country'])
            user1.gender = decrypt_data(data_post['gender'])
            user1.language = decrypt_data(data_post['language'])
            user1.nickName = decrypt_data(data_post['nickName'])
            user1.province = decrypt_data(data_post['province'])
            user1.token = hashlib.sha1(os.urandom(24)).hexdigest()
            user1.save()
            data = user.objects.get(OpenID=date['openid'])
        except:
            print(date)
            user1 = user(OpenID=date['openid'], session_key=date['session_key'], avatarUrl=decrypt_data(data_post['avatarUrl']),
                         city=decrypt_data(data_post['city']), country=decrypt_data(data_post['country']), gender=decrypt_data(data_post['gender']),
                         language=decrypt_data(data_post['language']), nickName=decrypt_data(data_post['nickName']), province=decrypt_data(data_post['province']),
                        token=hashlib.sha1(os.urandom(24)).hexdigest())
            user1.save()
            data = user.objects.get(OpenID=date['openid'])

        # data = json.loads(data)
        print(data)

        return JsonResponse({
            'code': '0001',
            'data': {
                'jifen':data.jifen,
                'name':data.nickName,
                'headimg':data.avatarUrl,
                'id':data.id,
                'token':data.token,
                'openid':data.OpenID,
            },
            'msg': '用户登录成功'
        })

    return JsonResponse({
        'code': '0000',
        'data': 'null',
        'msg': '非法请求'
    })

#解码
def decrypt_data(inputdata):
    try:
    # URLDecode
        data = parse.unquote(inputdata)
        # base64decode
        data = base64.b64decode(data)
        # 读取密钥
        dir = os.path.abspath('.')
        private_key = RSA.import_key(
            open(dir+"/api/data/private_key.pem").read())
        # 使用 PKCS1_v1_5解密
        cipher_rsa = PKCS1_v1_5.new(private_key)
        # 当解密失败，会返回 sentinel
        sentinel = None
        ret = cipher_rsa.decrypt(data, sentinel)
        return ret.decode() #解码
    except:
        return False
#自定义注解 过滤GET和POST请求解码 。

def create_rsa_key():
    """
    创建RSA密钥
    步骤说明：
    1、从 Crypto.PublicKey 包中导入 RSA，创建一个密码
    2、生成 1024/2048 位的 RSA 密钥
    3、调用 RSA 密钥实例的 exportKey 方法，传入口令、使用的 PKCS 标准以及加密方案这三个参数。
    4、将私钥写入磁盘的文件。
    5、使用方法链调用 publickey 和 exportKey 方法生成公钥，写入磁盘上的文件。
    """
    # 利用伪随机数来生成私钥和公钥
    random_generator = Random.new().read

    key = RSA.generate(2048,random_generator) #生成 1024/2048 位的 RSA 密钥
    encrypted_key = key.exportKey() #密钥实例
    dir = os.path.abspath('.')
    with open(dir+"/api/data/private_key.pem", "wb") as f:#私钥写入磁盘
        f.write(encrypted_key)
    with open(dir+"/api/data/public_key.pem", "wb") as f: #公钥写入磁盘
        f.write(key.publickey().exportKey())






def get_user_word(request):
    if request.method == 'POST':
        data_post = eval(request.body)
        print(data_post['id'])
        print(decrypt_data(data_post['id']))
        try:
            dds = user.objects.get(id=decrypt_data(data_post['id']), token=decrypt_data(data_post['token']))
            return JsonResponse({
                'code': '0011',
                'data': {
                'jifen':dds.jifen,
                'name':dds.nickName,
                'headimg':dds.avatarUrl
                },
                'msg': '数据获取成功'
            })
        except:
            return JsonResponse({
                'code': '0010',
                'data': '',
                'msg': '数据获取失败'
            })

    else:
        return JsonResponse({
            'code': '0000',
            'data': 'null',
            'msg': '非法请求'
        })


def All_in(request):
    print(request.method)
    if request.method == 'POST':
        data_post = eval(request.body)
        # data_post = json.loads(data_post)
        print(data_post['code'])


        if data_post['code'] == '0010':
            # 读取密钥
            dirs = os.path.abspath('.')
            private_key = open(dirs + "/api/data/public_key.pem").read()
            print(private_key)
            return JsonResponse({
                'code': '0011',
                'data': {
                    'key':private_key
                },
                'msg': '数据获取成功'
            })
        elif data_post['code'] == '0020':
            # 获取签到列表
            # 需要用户的key
            # 然后没别的了
            id = decrypt_data(str(data_post['data']['id']))
            token = decrypt_data(data_post['data']['token'])

            try:
                user.objects.get(id=id, token=token)
                qd_list = sig_user_task.objects.filter(xianshi=True)
                jieguo = []
                jinrishijian = time.strftime("%Y-%m-%d", time.localtime())
                print(dir(qd_list))
                for A in qd_list:
                    # data_qd = sig_user_task.objects.get(id=id, token=token)
                    # 获取到ID后查询
                    #     如果有就获取状态列表
                    #     没有就创建并获取/存在疑问判断好还是创建好
                    print(A.id)
                    try:
                        timp = sig_user_jl.objects.get(time=jinrishijian,sig_id=A.id,sig_user_id=id)
                        print(dir(timp))
                        jieguo.insert(0,{
                            'id': timp.id,
                            'img_url': A.img_url,
                            'task_start_date': A.task_start_date,
                            'task_end_date': A.task_end_date,
                            'Zhuang_tai': timp.Zhuang_tai

                        })
                        print('发现记录')
                    except:
                        print('没发现记录开始创建')
                        ddr = sig_user_jl(sig_id=A.id,Zhuang_tai=False,time=jinrishijian,sig_user_id=id)
                        ddr.save()
                        print('创建完成开始保存')
                        timp = sig_user_jl.objects.get(time=jinrishijian, sig_id=A.id,sig_user_id=id)
                        print(dir(timp))
                        jieguo.append({
                            'id': timp.id,
                            'img_url': A.img_url,
                            'task_start_date':A.task_start_date,
                            'task_end_date':A.task_end_date,
                            'Zhuang_tai':timp.Zhuang_tai

                        })
                        print('保存完成')
                # 切记位置此位置为循环结束返回
                return JsonResponse({
                    'code': '0020',
                    'data': jieguo,
                    'msg': '签到列表获取'
                })

            except:
                return JsonResponse({
                    'code': '0021',
                    'data': '',
                    'msg': '错误'
                })

        elif data_post['code'] == '0030':
            # 执行签到
            # 需要用户ID
            # 唯一ID
            # 临时token
            # 签到ID
            # 第一步是检测用户登录信息是否正确
            #     第二部是对用户的签到检测有没有执行过
            #         第三步检测用户签到时间段正确与否
            #             以上全部通过执行ID增加积分
            jinrishijian = time.strftime("%Y-%m-%d", time.localtime())
            jinrishijians = time.strftime("%H:%M:%S", time.localtime())
            re_data = {
                'code':'0010',
                'data':'',
                'msg':'数据获取失败'
            }
            ID = decrypt_data(str(data_post['data']['id']))
            print(ID)
            # 用户ID
            Token = decrypt_data(data_post['data']['token'])
            print(Token)
            # 临时token
            OpenID = decrypt_data(data_post['data']['openid'])
            print(OpenID)
            # 开放ID
            sig_user_task_id = decrypt_data(data_post['data']['sig_user_task_id'])
            print(sig_user_task_id)
            # 签到ID
            boo_user = user.objects.filter(id=ID, token=Token,OpenID=OpenID)
            if boo_user.exists():
                # 用户信息正确
                boo_sig = sig_user_jl.objects.filter(id=sig_user_task_id,sig_user_id=ID,time=jinrishijian)
                if boo_sig.exists():
                    print(boo_sig[0].Zhuang_tai)
                    # 最后一部检测时间范围
                    if boo_sig[0].Zhuang_tai == False:
                        boo_sig_A = sig_user_task.objects.filter(id=boo_sig[0].sig_id, xianshi=True)
                        if boo_sig_A.exists():
                            print(boo_sig_A[0].task_start_date)
                            print(boo_sig_A[0].task_end_date)
                            print('执行位置')
                            bool_this = time_b_z_s(boo_sig_A[0].task_start_date, jinrishijians,
                                                   boo_sig_A[0].task_end_date)
                            if bool_this:
                                # 如果为真说明时间对上了
                                # 最后都对上就可以执行签到了
                                print('~~~~~~~~~~~~~~~~~~~~')
                                print(boo_sig[0].id)
                                boo_sig[0].Zhuang_tai = True
                                ls_js_a = boo_sig_A[0].task_jifen
                                ls_jf = boo_user[0].jifen
                                ls_js_2 = int(ls_jf) + int(ls_js_a)
                                boo_siga = sig_user_jl.objects.filter(id=sig_user_task_id, sig_user_id=ID,
                                                                     time=jinrishijian)
                                if boo_siga.exists():
                                    print(boo_siga[0].Zhuang_tai)
                                    # 最后一部检测时间范围
                                    if boo_siga[0].Zhuang_tai == False:
                                        sig_user_jl.objects.filter(id=sig_user_task_id).update(Zhuang_tai=True,
                                                                                               jieshu_shijian=datetime.now())
                                        user.objects.filter(id=ID, token=Token, OpenID=OpenID).update(
                                            jifen=int(ls_js_2))

                                        re_data['msg'] = '签到成功'
                                        re_data['code'] = '0031'
                                        re_data['data'] = {
                                            'jifen': str(ls_js_a)
                                        }
                                    else:
                                        re_data['msg'] = '别破解了~'
                                else:
                                    re_data['msg'] = '别破解了~'

                            else:
                                # 不用说也知道时间不对
                                re_data['msg'] = '错误！！！！！'
                        else:
                            re_data['msg'] = '别破解了~'
                    else:
                        re_data['msg'] = '别破解了~'
                else:
                    re_data['msg'] = '破解？'

            else:
                print('用户信息不正确')
                re_data['msg'] = False
                pass
            return JsonResponse(re_data)


        else:
            # 不是指定类型返回获取失败
            return JsonResponse({
                'code': '0010',
                'data': '',
                'msg': '数据获取失败'
            })
    else:
        return JsonResponse({
            'code': '0000',
            'data': 'null',
            'msg': '非法请求'
        })

